package translinkApp.Data.DataTypes;

import java.io.Serializable;
import java.util.Calendar;

import android.os.Parcel;
import android.os.Parcelable;

public class Time implements Serializable, Parcelable {

	private static final long serialVersionUID = 148132749583919159L;
	private int hour;
	private int minute;
	private AmPm amPm;
	
	public Time() {
		this(-1, -1);
	}

	public Time(String timeString) {
		String[] split = timeString.split(":");

		if (split.length == 1) {
			split = timeString.split("\\.");
		}

		hour = Integer.parseInt(split[0]);
		minute = Integer.parseInt(split[1].substring(0, 2));

		String amPmType = split[1].substring(2, 4);

		if (amPmType.equals("am")) {
			setAmPm(AmPm.AM);
		} else {
			setAmPm(AmPm.PM);
			hour += 12;
		}
	}
	
	public Time(int hour, int minute, AmPm ampm) {
		this.hour = hour;
		this.minute = minute;
		this.setAmPm(ampm);

		if (amPm == AmPm.PM) {
			this.hour += 12;
		} else {
			if (hour == 12) {
				this.hour = 0;
			}
		}
	}

	public Time(int hour24, int minute) {
		
		if ((hour24 == -1) && (minute == -1) ) {
			Calendar c = Calendar.getInstance();
			hour24 = c.get(Calendar.HOUR_OF_DAY);
			minute = c.get(Calendar.MINUTE);
		}

		this.hour = hour24;
		setAmPm(AmPm.AM);
		if (hour24 >= 12) {
			setAmPm(AmPm.PM);
		}

		if (hour == 0) {
			hour = 12;
		}

		this.minute = minute;

	}
	
	public Time(Time time) {
		setHour(time.getHour());
		setMinute(time.getMinute());
		setAmPm(time.getAmPm());
	}

	public int getHour() {
		return hour;
	}

	public int getHourMeridian() {
		if (hour > 12) {
			return hour - 12;
		}
		return hour;
	}

	public void setHour(int hour) {
		this.hour = hour;
	}

	public int getMinute() {
		return minute;
	}

	public void setMinute(int minute) {
		this.minute = minute;
	}

	@Override
	public String toString() {

		return "" + ((hour <= 12) ? hour : (hour - 12)) + ":"
				+ ((new Integer(minute).toString().length() == 1) ? "0" + minute : minute)
				+ getAmPm().toString();
	}

	public void setAmPm(AmPm amPm) {
		this.amPm = amPm;
	}

	public AmPm getAmPm() {
		return amPm;
	}

	public enum AmPm {

		AM, PM
	}
	
	// ---- Parcellable object methods

	public Time(Parcel in) {
		setHour(in.readInt());
		setMinute(in.readInt());
		
		String s = in.readString(); 
		if (s != null) amPm = AmPm.valueOf(s);
	}

	public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
		public Time createFromParcel(Parcel in) {
			return new Time(in);
		}

		public Time[] newArray(int size) {
			return new Time[size];
		}
	};

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeInt(getHour());
		dest.writeInt(getMinute());
		dest.writeString(getAmPm() == null ? null : getAmPm().name());

	}

	@Override
	public int describeContents() {

		return 0;
	}
}
